<?php
class property extends Zcontroller {
	function __construct() {
		parent::__construct();
		//menu current page
		Zsession::setDataToSession("current_page", "property");	
			
	}
		
	//public $data="property";
		public function index($test = null)
		{ 
			
			$this->load->model("m_property");
			//load pagination class
			$this->load->library('pagination');
			$config['base_url'] = site_url("/property/index");
			$config['total_rows'] = $this->db->count_all('property');
			$config['per_page'] = '26';
			$config['num_links'] = '9';
			$config['full_tag_open'] = '<p>';
			$config['full_tag_close'] = '</p>';
			$this->pagination->initialize($config);			
			
			//$data["current_page"]="property";
			//load the model and get results
			
			$data['get_loc']=$this->m_property->get_loc_pro();
			$data['pro_cat']=$this->m_property->property_category();
	        $data['results']=$this->m_property->get_properties($config['per_page'],$this->uri->segment(3));
	        
			
			$this->load->template("templates/general","properties","The best propeties in cambodia", $data); 
		}
		
		function p(){	
			$Z_USER = Zsession::getUserFromSession(); 
			if(isset($Z_USER["user_id"])){
				$this->load->model("m_property");
				$data["success_message"] = Zsession::getFlash("success_message");
				$data["get_property"]=$this->m_property->get_properties('0','0');
				$data['pro_cat']=$this->m_property->property_category();
				$data["get_loc"]=$this->m_property->get_loc_pro();
				$this->load->template("templates/general","insert_property","The best propeties in cambodia", $data); 
			}else {
			redirect(site_url("users"));
			}	
		}
		
		function u(){
			$this->load->model("m_property");
			$Z_USER = Zsession::getUserFromSession(); 
			if(isset($Z_USER["user_id"])){				
				$id=isset($_GET["proid"]) ? $_GET["proid"] : null;	         			
        		$id = Zencryption::decrypt($id);
        		$id = unserialize($id);
        		
        		$data["success_message"] = Zsession::getFlash("success_message");
				$data["get_property"]=$this->m_property->get_property_id($id);
				$data["get_pic_id"]=$this->m_property->get_pic_id($id);
				$data['pro_cat']=$this->m_property->property_category();
				$data["get_loc"]=$this->m_property->get_loc_pro();
				$this->load->template("templates/general","edit_property","The best propeties in cambodia", $data); 
			}else 
			redirect(site_url(users));	
		}
		
		function del_property($proid){
			$this->load->model("m_property");
         	$Z_USER = Zsession::getUserFromSession(); 		
        	$proid = Zencryption::decrypt($proid);
        	$proid = unserialize($proid);
        	
			$this->m_property->del_property($proid);
			$this->m_property->del_property_pic($proid);
			$img_arr=$this->m_property->get_pic_id($proid);
    		$str_path = str_replace("\\", "/", FCPATH);
			//echo "<pre>"; var_dump($img_arr); echo "</pre>";
			
    		foreach ($img_arr->result_array() as $rowimg){
    			$file_path=$str_path."usr/".htmlspecialchars($Z_USER["user_id"]).'/'.$rowimg['pic_name'];
    			$file_name = current(explode(".", $rowimg['pic_name']));
    			$file_ext  = next(explode(".", $rowimg['pic_name']));
    			$file_path_thumb=$str_path."usr/".htmlspecialchars($Z_USER["user_id"]).'/'.$file_name."_Thumb.".$file_ext;
    	 		
    			if(file_exists($file_path)){ 
    				unlink($file_path);
    				unlink($file_path_thumb);
    			};
    		}
			redirect($_SERVER['HTTP_REFERER']);	
		}
		
		function renew($property_id){
			$this->load->model("m_property");	
			$Z_USER = Zsession::getUserFromSession(); 
			if(isset($Z_USER["user_id"])){
				$type = serialize("properties");
				$this->m_property->renew($property_id);
				Zsession::setFlash("success_message", "Property ads has been renewed successfully");
				redirect(site_url("users/profiles?type=".Zencryption::encrypt($type)));
			}else {
				redirect(site_url(users));
			}
		}	
		
		function del_pic($proid,$pic){
			$this->load->model("m_property");
			
			$img_arr=$this->m_property->get_pic_id($proid);
    		$str_path = str_replace("\\", "/", FCPATH);
    		
			$this->m_property->del_pic($pic);
			
			$file_path=$str_path."usr/".htmlspecialchars($Z_USER["user_id"]).'/'.$rowimg['pic_name'];
    		$file_name = current(explode(".", $rowimg['pic_name']));
    		$file_ext  = next(explode(".", $rowimg['pic_name']));
    		$file_path_thumb=$str_path."usr/".htmlspecialchars($Z_USER["user_id"]).'/'.$file_name."_Thumb.".$file_ext;
    	 		
    		if(file_exists($file_path)){ 
    				unlink($file_path);
    				unlink($file_path_thumb);
    		};
			redirect($_SERVER['HTTP_REFERER']);	
		}
		
		function detail($id){
			$this->load->model("m_property");
			$this->load->model("m_users");
			$data["get_property"]=$this->m_property->get_property_id($id);
			$data["get_pic_id"]=$this->m_property->get_pic_id($id);
			$data['pro_cat']=$this->m_property->property_category();
			$data["get_loc"]=$this->m_property->get_loc_pro();
			
			$user_upload=$this->m_property->get_property_id($id);
			$user_id=$user_upload["user_upload"];

			$data['user_info']=$this->m_property->get_user_id($user_id);
			
			$this->m_property->insert_property_hit($id);
			$this->load->template("templates/general","detail_property","The best propeties in cambodia", $data); 
		}
		
		function ext_check1(){
			//echo "<pre>";var_dump($_FILES);echo "</pre>";
			return $this->ext_check("image1");
        }
        
		function ext_check2(){
			return $this->ext_check("image2");
        }
        
		function ext_check3(){
			return $this->ext_check("image3");
        }
        
		function ext_check4(){
			return $this->ext_check("image4");
        }
        
		function ext_check5(){
			return $this->ext_check("image5");
        }
        
        function ext_check($obj_name) {
        	$allowedExt = array("jpg","jpeg","gif","png","JPG","GIF","PNG","JPEG");
        	switch ($obj_name) {
        		case "image1" : $function_name = "ext_check1"; break;
        		case "image2" : $function_name = "ext_check2"; break;
        		case "image3" : $function_name = "ext_check3"; break;
        		case "image4" : $function_name = "ext_check4"; break;
        		case "image5" : $function_name = "ext_check5"; break;
        		default : $function_name = "ext_check1"; break;
        	}
			
			if (isset($_FILES) && isset($_FILES[$obj_name]) && isset($_FILES[$obj_name]["tmp_name"]) && $_FILES[$obj_name]["tmp_name"]!= "") {
				$file_ext = next(explode(".", $_FILES[$obj_name]["name"]));
				if (!in_array($file_ext, $allowedExt)) {
					$this->form_validation->set_message($function_name, 'The %s (<font color=blue>'.$_FILES[$obj_name]["name"].'</font>) is not an image file.'); 
					return false;
				}
			}
			return true;
        }
		
        
		function gonew_property(){
			$this->load->model("m_property");
			$this->load->library("image_lib");
			$this->load->helper("url_helper");
		    $Z_USER = Zsession::getUserFromSession();
			$this->load->library('form_validation'); 
			
				//echo $file_ext = next(explode(".", $_POST["image1"]));
				
		     	$this->form_validation->set_rules('txtTitle', 'Title', 'required');

		     		
		     	$this->form_validation->set_rules('image1', 'Picture 1', "callback_ext_check1");	
		     	$this->form_validation->set_rules('image2', 'Picture 2', 'callback_ext_check2');
		     	$this->form_validation->set_rules('image3', 'Picture 3', 'callback_ext_check3');
		     	$this->form_validation->set_rules('image4', 'Picture 4', 'callback_ext_check4');
		     	$this->form_validation->set_rules('image5', 'Picture 5', 'callback_ext_check5');
		     	
				$this->form_validation->set_rules('cb_loc', 'Location', 'required');
				$this->form_validation->set_rules('cbo_type', 'Property Type', '');
				$this->form_validation->set_rules('cbo_cat', 'Property Category', '');
				$this->form_validation->set_rules('cbo_Floor', 'floors', '');
				$this->form_validation->set_rules('cbo_Bedroom', 'bedrooms', '');
				$this->form_validation->set_rules('cbo_parking', 'parking', '');
				$this->form_validation->set_rules('cbo_bath', 'bath', '');
				$this->form_validation->set_rules('txtFeatures', 'Features', '');
				$this->form_validation->set_rules('txtDesc', 'Description', '');
				$this->form_validation->set_rules('txtPrice', 'Price', '');
				$this->form_validation->set_rules('txtBSize', 'Building Size', '');
				$this->form_validation->set_rules('txtLSize', 'Landing Size', '');
				$this->form_validation->set_rules('captcha', 'Security Code', 'required|callback_captcha_check');
				//$this->ext_check();
				if ($this->form_validation->run() == FALSE)
				{	
					$data["get_property"]=$this->m_property->get_property();
					$data["get_loc"]=$this->m_property->get_loc_pro();
					$data['pro_cat']=$this->m_property->property_category();			
					$data['message_errors'] = validation_errors();
					$this->load->template("templates/general","insert_property","New post ads property ",$data);
				}
				else{				     

				      /* Create the config for upload library */
				      /* (pretty self-explanatory) */
				      $date=date("His");
				      $patch=FCPATH."/usr/".htmlspecialchars($Z_USER["user_id"])."/"; /* NB! create this dir! */
				      if (!file_exists ($patch)){ mkdir($patch,0777);}
				      $config["upload_path"] = $patch;
				      $config["allowed_types"] = "gif|jpg|png|bmp|jpeg";		      
				      $config["image_library"] = "gd2";
				      $config["source_image"] = $patch.htmlspecialchars($Z_USER["user_id"]);
				      $config["encrypt_name"]  = FALSE;
				      //$config["overwrite"]  = TRUE;
				      $config["max_size"]  = "0";
				      $config["max_width"]  = "0";
				      $config["max_height"]  = "0";
		
				      /* Load the upload library */
				      $this->load->library("upload", $config);
				
				      /* Create the config for image library */
				      /* (pretty self-explanatory) */
				      $configThumb = array();
				      $configThumb["image_library"] = "gd2";
				      $configThumb["thumb_marker"] = $date."_Thumb";
				      $configThumb["source_image"] = "";
				      $configThumb["create_thumb"] = TRUE;
				      $configThumb["maintain_ratio"] = TRUE;
				      /* Set the height and width or thumbs */
				      /* Do not worry - CI is pretty smart in resizing */
				      /* It will create the largest thumb that can fit in those dimensions */
				      /* Thumbs will be saved in same upload dir but with a _thumb suffix */
				      /* e.g. 'image.jpg' thumb would be called 'image_thumb.jpg' */
				      $configThumb["width"] = 68;
				      $configThumb["height"] = 60;
				      /* Load the image library */
				      $this->load->library("image_lib");
						      
				      $filename_arr = array();
				      $filename_big_arr = array();
				      
				      $file_path='usr/'.htmlspecialchars($Z_USER["user_id"]).'/';
									 
					  $prop_id = $this->m_property->insert_properties($_POST["txtTitle"],	
												     $_POST["cb_loc"],
												     $_POST["cbo_type"],
													 $_POST["cbo_Floor"],
													 $_POST["cbo_Bedroom"],
													 $_POST["txtFeatures"],
													 $_POST["txtDesc"],
													 $_POST["txtPrice"],
													 $_POST["txtBSize"],
													 $_POST["txtLSize"],
													 $file_path,
													 $_POST["cbo_bath"],
													 $Z_USER["user_id"],
													 $_POST["cbo_parking"],
													 $_POST["cbo_cat"]);
				      
				      for($i = 1; $i <= count($_FILES); $i++) {
				        /* Handle the file upload */
				        $upload = $this->upload->do_upload("image".$i);
				        /* File failed to upload - continue */
				           
				      	if($upload === FALSE) continue;
				        	/* Get the data about the file */
				        	$data = $this->upload->data();
				        
				        	$uploadedFiles[$i] = $data;
				        	/* If the file is an image - create a thumbnail */
					        if($data["is_image"] == 1) {
					          $filename_arr["image".$i] = $data["orig_name"];
					
					          //$_FILES["image".$i]['name'];
					          $configThumb["source_image"] = $data["full_path"];     
					          
					          $this->image_lib->initialize($configThumb);
					          $this->image_lib->resize();
					           
					          //echo "<pre>"; var_dump($data); echo "</pre>";
					          $filename = $data["file_path"].$data["raw_name"].$date.$data["file_ext"];
					          //$filename = $data["raw_name"].'_big'.$data['file_ext'];
			
							  $image_obj = new Zimage();
            				  $image_obj->resize($data["full_path"], $filename);
					          //rename($data["full_path"], $filename);
					          $filename_big_arr["image".$i] = $data["raw_name"].$date.$data["file_ext"];
				  			  
					          $this->m_property->insert_pic_by_id($prop_id,$filename_big_arr["image".$i]);	
					          //echo "<br/>".$filename_big_arr["image".$i];		  			  
					        }else{
	 
							  //$this->m_property->insert_pic_by_id($pic_id,"");
			  			  
					      	}//end if $data is image
				       
				    	 } // FOR LOOP
		    	  
                											
                  		Zsession::setFlash("success_message", "Property has been saved successfully");
                  		redirect(site_url('users/profiles?type='.Zencryption::encrypt(serialize("properties"))));
                  		//echo "<pre>"; var_dump($img_arr); echo "</pre>";
                  		//echo "<div class=\"sucessfully\"><h3>Property have been inserted sucessfully.</h3></div>";
				 		//$auto="<script type=\"text/javascript\">setInterval( \"autosubmit()\", 1600 );function autosubmit(){ document.location=\"".site_url('users/profiles?type='.Zencryption::encrypt(serialize("properties")))."\";}</script>";
				 		///echo $auto;  
				}
		}
		
        function captcha_check(){
        	if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) 
			{	
				$request_captcha = htmlspecialchars($_REQUEST['captcha']);
				$captcha_message = "Invalid code, Please try again!";
        		$request_captcha = htmlspecialchars($_REQUEST['captcha']);
				$this->form_validation->set_message('captcha_check', '<div style=\"background-color: #FF606C; width:160px; height:50px; padding:5px;\">'.$captcha_message.'</div>');				
				//$data["captcha_message"]="<div style=\"background-color: #FF606C; width:160px; height:50px; padding:5px;\"><h2>$captcha_message</h2></div>";   				 
				return FALSE;
			}
        	else
			{
			return TRUE;
			}
        }


		function update_property(){
			$this->load->model("m_property");
			$this->load->library("image_lib");
			$this->load->helper("url_helper");
		    $Z_USER = Zsession::getUserFromSession();
			$this->load->library('form_validation'); 

		    $this->form_validation->set_rules('txtTitle', 'Title', 'required');
		    $this->form_validation->set_rules('image1', 'Please upload images', '');
		    $this->form_validation->set_rules('image2', 'Please upload images', '');
		    $this->form_validation->set_rules('image3', 'Please upload images', '');
		    $this->form_validation->set_rules('image4', 'Please upload images', '');
		    $this->form_validation->set_rules('image5', 'Please upload images', '');
			$this->form_validation->set_rules('cb_loc', 'Location', 'required');
			$this->form_validation->set_rules('cbo_type', 'Property Type', '');
			$this->form_validation->set_rules('cbo_Floor', 'Floors', '');
			$this->form_validation->set_rules('cbo_Bedroom', 'Bedrooms', '');
			$this->form_validation->set_rules('cbo_parking', 'parking', '');
			$this->form_validation->set_rules('cbo_bath', 'bath', '');
			$this->form_validation->set_rules('txtFeatures', 'Features', '');
			$this->form_validation->set_rules('txtDesc', 'Description', '');
			$this->form_validation->set_rules('txtPrice', 'Price', '');
			$this->form_validation->set_rules('txtBSize', 'Building Size', '');
			$this->form_validation->set_rules('txtLSize', 'Landing Size', '');
			$this->form_validation->set_rules('cbo_cat', 'Category', 'required');
			//$this->form_validation->set_rules('captcha', 'Security Code', 'required|callback_captcha_check');
				
			if ($this->form_validation->run() == FALSE)
			{	
				$data["get_property"]=$this->m_property->get_property_id($_POST["txtID"]);
				//$data["get_property"][]
				$data["get_loc"]=$this->m_property->get_loc_pro();
				$data['pro_cat']=$this->m_property->property_category();
				$data['pro_cat']=$this->m_property->property_category();			
				$data['message_errors'] = validation_errors();
				$data["get_pic_id"]=$this->m_property->get_pic_id($_POST["txtID"]);
				$this->load->template("templates/general","edit_property","Edit post ads property ",$data);
			}else{				     

					  /* Create the config for upload library */
				      /* (pretty self-explanatory) */
				      $date=date("His");
				      $patch=FCPATH."/usr/".htmlspecialchars($Z_USER["user_id"])."/"; /* NB! create this dir! */
				      if (!file_exists ($patch)){ mkdir($patch,0777);}
				      $config["upload_path"] = $patch;
				      $config["allowed_types"] = "gif|jpg|png|bmp|jpeg";		      
				      $config["image_library"] = "gd2";
				      $config["source_image"] = $patch.htmlspecialchars($Z_USER["user_id"]);
				      $config["encrypt_name"]  = FALSE;
				      //$config["overwrite"]  = TRUE;
				      $config["max_size"]  = "0";
				      $config["max_width"]  = "0";
				      $config["max_height"]  = "0";
		
				      /* Load the upload library */
				      $this->load->library("upload", $config);
				
				      /* Create the config for image library */
				      /* (pretty self-explanatory) */
				      $configThumb = array();
				      $configThumb["image_library"] = "gd2";
				      $configThumb["thumb_marker"] = $date."_Thumb";
				      $configThumb["source_image"] = "";
				      $configThumb["create_thumb"] = TRUE;
				      $configThumb["maintain_ratio"] = TRUE;
				      /* Set the height and width or thumbs */
				      /* Do not worry - CI is pretty smart in resizing */
				      /* It will create the largest thumb that can fit in those dimensions */
				      /* Thumbs will be saved in same upload dir but with a _thumb suffix */
				      /* e.g. 'image.jpg' thumb would be called 'image_thumb.jpg' */
				      $configThumb["width"] = 68;
				      $configThumb["height"] = 60;
				      /* Load the image library */
				      $this->load->library("image_lib");
						      
				      $filename_arr = array();
				      $filename_big_arr = array();
				      
				      $file_path='usr/'.htmlspecialchars($Z_USER["user_id"]).'/';
					  $this->m_property->update_properties($_POST["txtID"],
										 $_POST["txtTitle"],	
									     $_POST["cb_loc"],
									     $_POST["cbo_type"],
										 $_POST["cbo_Floor"],
										 $_POST["cbo_Bedroom"],
										 $_POST["txtFeatures"],
										 $_POST["txtDesc"],
										 $_POST["txtPrice"],
										 $_POST["txtBSize"],
										 $_POST["txtLSize"],
										 $_POST["txtID"],
										 $file_path,
										 $_POST["cbo_bath"],
										 $_POST["cbo_parking"],
										 $_POST["cbo_cat"]);
										 
				      for($i = 1; $i <= count($_FILES); $i++) {
				        /* Handle the file upload */
				        $upload = $this->upload->do_upload("image".$i);
				        /* File failed to upload - continue */
				           
				      	if($upload === FALSE) continue;
				      	//if($upload === TRUE){
				        	/* Get the data about the file */
				        	$data = $this->upload->data();
				        
				        	$uploadedFiles[$i] = $data;
				        	/* If the file is an image - create a thumbnail */
					        if($data["is_image"] == 1) {
					          $filename_arr["image".$i] = $data["orig_name"];
					
					          //$_FILES["image".$i]['name'];
					          $configThumb["source_image"] = $data["full_path"];     
					          
					          $this->image_lib->initialize($configThumb);
					          $this->image_lib->resize();
					           
					          //echo "<pre>"; var_dump($data); echo "</pre>";
					          $filename = $data["file_path"].$data["raw_name"].$date.$data["file_ext"];
					          //$filename = $data["raw_name"].'_big'.$data['file_ext'];
			
							  $image_obj = new Zimage();
            				  $image_obj->resize($data["full_path"], $filename);
					          //rename($data["full_path"], $filename);
					          $filename_big_arr["image".$i] = $data["raw_name"].$date.$data["file_ext"];			

                              $this->m_property->insert_pic_by_id($_POST["txtID"],$filename_big_arr["image".$i]);
                              
                              unlink($data["full_path"]);
							  $this->image_lib->clear();
            				  unset($config);
					        }/* is images*/
				    }// for loop
													 		  
					//echo "<div class=\"sucessfully\"><h3>Property have been updated sucessfully.</h3></div>";
					//$auto="<script type=\"text/javascript\">setInterval( \"autosubmit()\", 1600 );function autosubmit(){ document.location=\"".site_url('users/profiles?type='.Zencryption::encrypt(serialize("properties")))."\";}</script>";
				 	//$auto="<script type=\"text/javascript\">setInterval( \"autosubmit()\", 1600 );function autosubmit(){ document.location=\"".site_url('property/u?proid='.Zencryption::encrypt(serialize($_POST["txtID"])))."\";}</script>";
				  	//redirect($_SERVER['HTTP_REFERER']);
				  	Zsession::setFlash("success_message", "Update has been saved successfully");
                  	redirect(site_url('property/u?proid='.Zencryption::encrypt(serialize($_POST["txtID"]))));
				
			}//end form validation

		}//end function
		
		function search(){
			$this->load->model("m_property");	
			$this->load->database();
			$criteria = array();		
			$criteria["ref"] = $_GET['q'];
			$criteria["loc"]=$_GET['specify'];
			$criteria["price_min"]=$_GET['min'];
			$criteria["price_max"]=$_GET['max'];
			$criteria["type"]=$_GET['searchType'];
			$criteria["cat"] = $_GET['cbo_cat'];
			//$this->uri->segment(3)
			
			//load pagination class
			$this->load->library('pagination');
			$offset = isset($_GET["per_page"]) && $_GET["per_page"]!="" ? $_GET["per_page"] : "0";
			
			$config['page_query_string'] = TRUE;
			$config['per_page'] = '26';
			$config['num_links'] = '9';
			
			$config['base_url'] = site_url("/property/search"."?q=".$_GET['q']."&specify=".$_GET['specify']."&min=".$_GET['min']."&max=".$_GET['max']."&searchType=".$_GET['searchType']."&cbo_cat=".$_GET['cbo_cat']);
			$config['total_rows'] = $this->m_property->get_result($criteria,"")->num_rows();
			//echo $config['total_rows'];
			
			$config['full_tag_open'] = '<p>';
			$config['full_tag_close'] = '</p>';
			$this->pagination->initialize($config);

			//load the model and get results			
			$data['get_loc']=$this->m_property->get_loc_pro();
			$data['pro_cat']=$this->m_property->property_category();
			$data['get_search']=$this->m_property->get_result($criteria,$config['per_page'],$offset);
			$this->load->template("templates/general","result_property","The best propeties in cambodia",$data);

		}
				
		
		function test(){
			$this->load->model("m_property");
			$Z_USER = Zsession::getUserFromSession();				
			$id=$this->m_property->get_last_id();
			$date=date('His');
			echo $id['property_id'];
			echo Zencryption::encrypt(serialize('testtest'.$date));
		}
		
}

?>